//
//  SecurityHomeVC.swift
//  SBSafetyApp
//
//  Created by Aimeow on 2022/11/16.
//  保安管理-首页

import Foundation
import UIKit

class SecurityHomeVC: SubLevelViewController {
    
    var modal: SignVerifyModel?
    var selectDept: DeptModal?

    var param = ClockInParam()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setupUI()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navBarStyle(.clear)
        reloadData()
        verifyLoc()
//        navigationController?.setNavigationBarHidden(true, animated: animated)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
//        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    
    func reloadData() {
        // 签到验证
        API.getCheckSign { responseModel in
            self.modal = responseModel.model
            DispatchQueue.main.async {
                self.updateUI()
            }
        }
    }
    
    func updateUI() {
        checkInListView.buildData(models: modal?.list ?? [])
        emptyView.isHidden = (modal?.list ?? []).count > 0
        checkButton.setTitle(modal?.signBtnStatus == true ? "签退" : "签到", for: .normal)
        panelView.checkInItem.title = modal?.signBtnStatus == true ? "签退" : "签到"
    }
    
    func verifyLoc() {
        LocManager.shared.didUpdateLocWith = { (longitude, latitude, address) -> () in
            let lngLat = "\(longitude),\(latitude)"
            self.param.location = address
            self.param.lngLat = lngLat
        }
        LocManager.shared.startLoaction()
    }
    
    // 签到/签退
    @objc func checkInOrOut() {
        if self.modal?.signBtnStatus == true  { // 签退（已签到）
            let signM = self.modal?.list?[0]
            self.selectDept?.deptId = signM?.signDeptId
            self.selectDept?.deptName = signM?.signDeptName
            self.selectDept?.deptPosition = signM?.location
            self.param.signDeptId = signM?.signDeptId
            self.verifyFace(withNavi: navigationController)
        } else { // 签到
            let bsvc = BranchSearchVC()
            bsvc.didSelectBranchWith = { (dept, _) -> () in
                self.selectDept = dept
                self.param.signDeptId = dept.deptId
                self.verifyFace(withNavi: bsvc.navigationController)
            }
            navigationController?.pushViewController(bsvc, animated: true)
        }
    }
    
    func verifyFace(withNavi navi: UINavigationController?, isPop: Bool = false) {
        if param.location == nil {
            Utils.app.window?.showToast(witMsg: "请确认已开启定位服务!")
            return
        }
        
        let fdvc = FaceDetectVC(withCheckValue: modal?.signBtnStatus == true ? "签退" : "签到")
        fdvc.didSelectImageWith = { (img) -> () in
//            self.param.imgStr = img.imgToBase64()
            fdvc.view.showToastActivity()
            self.verifyJson(withNavi: fdvc.navigationController, img: img)
        }
        if isPop == true {
//            navi?.popToViewController(fdvc, animated: true)
            navi?.pushViewController(fdvc, animated: true)
        } else {
            navi?.pushViewController(fdvc, animated: true)
        }
    }
    
    func verifyJson(withNavi navi: UINavigationController?, img: UIImage) {
        do {
            let data: Data = try JSONEncoder().encode(param)
            let string = String(data: data, encoding: String.Encoding.utf8) ?? ""
            let path = FilesManager.shared.saveImage(img: img)!
            API.postClockIn(withJsonStr: string, imagePath: path) { responseModel in
                DispatchQueue.main.async {
                    self.view.hideToastActivity()
                    if responseModel.errorCode == .Success {
                        let vc = CheckInSuccessVC()
                        vc.didDoTaskWith = {() -> () in
                            vc.navigationController?.popToRootViewController(animated: false)
                            self.navigationController?.pushViewController(SecurityTaskListVC(), animated: true)
                        }
                        vc.update(withSignStatus: self.modal?.signBtnStatus, selectDept: self.selectDept)
                        navi?.pushViewController(vc, animated: true)
                    } else {
                        let vc = CheckInFailedVC()
                        vc.didReFaceWith = {() -> () in
//                            self.param.imgStr = nil
                            self.verifyFace(withNavi: vc.navigationController)
                        }
                        vc.update(withSignStatus: self.modal?.signBtnStatus, msg: responseModel.errorMessage)
                        navi?.pushViewController(vc, animated: true)
                    }
                }
            }
        } catch  {
            print(self.modal?.signBtnStatus == true ? "签退失败" : "签到失败")
        }
    }

    func setupUI() {
        view.backgroundColor = .bg
        
        view.addSubview(checkButton)
        checkButton.snp.makeConstraints { make in
            make.height.equalTo(50)
            make.width.equalTo(220)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-16)
        }
        
        view.addSubview(panelView)
        panelView.snp.makeConstraints { make in
            make.top.equalToSuperview() //.offset(-UIDevice.navigationFullHeight())
            make.left.right.equalToSuperview()
        }

        view.addSubview(checkInTitleLabel)
        checkInTitleLabel.snp.makeConstraints { make in
            make.top.equalTo(panelView.snp.bottom).offset(10)
            make.centerX.equalToSuperview()
        }
        
        scrollView.showsVerticalScrollIndicator = false
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.top.equalTo(checkInTitleLabel.snp.bottom).offset(10)
            make.left.right.equalToSuperview()
            make.width.equalTo(ScreenWidth)
            make.bottom.equalTo(checkButton.snp.top).offset(-10)
        }
        
        scrollView.addSubview(emptyView)
        emptyView.snp.makeConstraints { make in
            make.width.left.right.equalToSuperview()
            make.top.equalTo(checkInTitleLabel.snp.bottom)
            make.bottom.equalTo(checkButton.snp.top)
        }
        
        scrollView.addSubview(checkInListView)
        checkInListView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        return scrollView
    }()

    lazy var panelView: SecurityHomePanelView = {
        let panelView = SecurityHomePanelView(frame: .zero)
        panelView.delegate = self
        return panelView
    }()

    lazy var checkInTitleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.hex("#000000")
        label.text = "今日签到记录"
        label.font = UIFont.systemFont(ofSize: 17)
        return label
    }()

    lazy var checkInListView: CheckInListView = {
        let view = CheckInListView(frame: .zero)

        return view
    }()

    lazy var emptyView: EmptyView = {
        let view = EmptyView()
        view.style = .qiandao
        return view
    }()

    lazy var checkButton: UIButton = {
        let button = UIButton.createCornerButton("签到")
        button.addTarget(self, action: #selector(checkInOrOut), for: .touchUpInside)
        return button
    }()
}

extension SecurityHomeVC: SecurityHomePanelTapDelegate {
    func taskItemTapped() {
        if modal?.signBtnStatus == true { // 已签到
            navigationController?.pushViewController(SecurityTaskListVC(), animated: true)
        } else {
            view.showToast(witMsg: "请先签到！")
        }
    }

    func checkInItemTapped() {
        checkInOrOut()
    }

    func statisticsItemTapped() {
        navigationController?.pushViewController(AttendanceStatisticsVC(), animated: true)
    }
}
